package cn.amoqi.springboot.rabbit.rabbit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 测试Confirm发送消息完成之后，有回调，消息持久化
 */

@Configuration
public class ConfirmRabbitConfig {
    public static final String QUEUE_NAME = "ConfirmRabbit.queue";
    public static final String EXCHANGE_NAME = "ConfirmRabbit.exchange";
    public static final String ROUTE_KEY_NAME = "ConfirmRabbit.routeKey";
    public static Logger logger = LoggerFactory.getLogger(ConfirmRabbitConfig.class);
    @Autowired
    CachingConnectionFactory cachingConnectionFactory;

    @Bean
    RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            String msgId = data.getId();
            if(ack){
                logger.info(msgId+":消息发送成功");
                //此处可以更改数据库消息成功状态
            }else{
                logger.info(msgId+":消息发送失败");
            }
        });
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingkey)->{
            logger.info("消息发送失败");
        });
        return rabbitTemplate;
    }

    @Bean
    Queue confirmQueue() {
        //QUEUE第二个参数为持久化
        return new Queue(ConfirmRabbitConfig.QUEUE_NAME, true);
    }

    @Bean
    DirectExchange mailExchange() {
        return new DirectExchange(EXCHANGE_NAME, true, false);
    }

    @Bean
    Binding mailBinding() {
        return BindingBuilder.bind(confirmQueue()).to(mailExchange()).with(ROUTE_KEY_NAME);
    }


}
